package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PressUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.AndroidScheduler;
import com.tjvib.widget.ItemGroup;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class InfoActivity extends BaseActivity {

    private RelativeLayout info_rl_icon;
    private ImageView info_iv_icon;
    private ItemGroup info_ig_phone, info_ig_name;

    private String username;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_info;
    }

    @Override
    protected boolean initView() {
        info_rl_icon = findViewById(R.id.info_rl_icon);

        info_iv_icon = findViewById(R.id.info_iv_icon);
        info_iv_icon.setOnClickListener(v -> startActivity(new Intent(InfoActivity.this, IconActivity.class)));

        info_ig_phone = findViewById(R.id.info_ig_phone);
        info_ig_phone.setOnClickListener(v -> ToastUtil.show("不可修改！"));

        info_ig_name = findViewById(R.id.info_ig_name);

        PressUtil.setPressChange(InfoActivity.this, info_iv_icon, info_rl_icon);
        return true;
    }

    @Override
    protected boolean initData() {
        Glide.with(InfoActivity.this).load(UserManager.getInstance().getImage()).into(info_iv_icon);

        info_ig_phone.setItem_group_et_con(UserManager.getInstance().getPhoneNumber());
        info_ig_name.setItem_group_et_con(UserManager.getInstance().getUsername());

        username = UserManager.getInstance().getUsername();

        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    //隐藏软键盘并让editText失去焦点
    private void hideKeyboard(IBinder token) {
        info_ig_name.clearFocus();
        if (!username.equals(info_ig_name.getContentEdit().getText().toString())) {
            LoadingDialog loadingDialog = new LoadingDialog(this);
            loadingDialog.showDialog(this, "提交修改中...");
            UserManager.getInstance().setUsername(info_ig_name.getContentEdit().getText().toString());
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                    UserManager.getInstance().getInfo());
            RetrofitHelper.getInstance().create()
                    .change_info(requestBody, String.valueOf(UserManager.getInstance().getUserId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidScheduler.mainThread())
                    .subscribe(new Observer<BaseResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(BaseResponse value) {
                            loadingDialog.dismiss();
                            if (value.getCode() == SUCCESS) {
                                ToastUtil.show("修改成功");
                                LogUtil.d(value.getMessage() + "\n" + value.getData());
                                username = info_ig_name.getContentEdit().getText().toString();
                            } else {
                                LogUtil.e(value.getCode() + "\n" + value.getMessage() + "\n" + value.getData());
                                showErrorDialog(value.getMessage());
                                UserManager.getInstance().setUsername(username);
                                info_ig_name.setItem_group_et_con(username);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            LogUtil.e("change_info response error");
                            showErrorDialog(e.getMessage());
                            loadingDialog.dismiss();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}